package com.example.interview.clone;

import lombok.Getter;
import lombok.Setter;

public class CloneDemo {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setName("张三");
        p1.setAge(18);
        // 引用类型
        Address address = new Address();
        address.setCity("北京");
        p1.setAddress(address);
        // 克隆 p1 对象
        Person p2 = p1.clone();
        // 对比引用类型的地址值是否相同
        System.out.println(p1.getAddress() == p2.getAddress()); // false
    }
}

@Getter
@Setter
class Person implements Cloneable {
    private String name;
    private int age;
    private Address address; // 引用类型

    @Override
    public Person clone() {
        Person person = null;
        try {
            person = (Person) super.clone();
            // 克隆引用类型
            person.setAddress(person.getAddress().clone());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }
}

@Getter
@Setter
class Address implements Cloneable {
    private String city;

    @Override
    public Address clone() {
        Address address = null;
        try {
            address = (Address) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return address;
    }
}
